/**
 * 各角色授权功能模块业务处理
 */
import {
  api,
  storage
} from '../util'
// 登录SessionKey
const goods_cache_key = "GoodsCachekey"
/**
 * 货品数量属性缓存
 */
class GoodsNumCache {
  // 构造函数
  constructor(productId, goodsId, num, radix) {
    this.productId = productId;
    this.goodsId = goodsId;
    this.num = num;
    this.radix = radix;
  }
  //批量添加
  static init(source) {
    var obj = {
      data: {},
      time: new Date().getTime()
    };
    source.map(function(item, i) {
      var entity = new GoodsNumCache(item.productId, item.goodsId, item.num, item.radix);
      obj.data[item.goodsId] = entity;
    });
    storage.put(goods_cache_key, obj, 0);
  }
  // 添加
  static add(productId, goodsId, num, radix) {
    var obj = storage.get(goods_cache_key) || {
      data: {},
      time: new Date().getTime()
    };
    var entity = new GoodsNumCache(productId, goodsId, num, radix);
    obj.data[goodsId] = entity;
    obj.time = new Date().getTime();
    storage.put(goods_cache_key, obj, 0);
  }
  // 删除
  static del(goodsId) {
    var obj = storage.get(goods_cache_key) || {
      data: {},
      time: new Date().getTime()
    };
    if (obj.data == null) storage.put(goods_cache_key, obj, 0);
    delete obj.data[goodsId];
    obj.time = new Date().getTime();
    storage.put(goods_cache_key, obj, 0);
  }
  /**
   * 比较时间
   */
  static compareTime(t) {
    var obj = storage.get(goods_cache_key);
    if (obj == null || obj == undefined) return false;
    if (t > obj.time) return false;
    return true;
  }
  //获得
  static getProductNum(productId, default_num,isSingle=true) {
    var obj = storage.get(goods_cache_key);
    if (obj == null || obj == undefined) return default_num;
    var sum = 0,
      bo = false,len=0;
    for (var key in obj.data) {
      len++;
      var entity = obj.data[key];
      if (entity == null || entity == undefined) continue;
      if (entity.productId == productId) {
        bo = true;
        if(!isSingle){
          sum += entity.num*entity.radix;
        }
        else{
          sum += entity.num;
        }

      }
    }
    if(len==0) bo=true;
    return bo ? sum : 0;
  }
  static clearGoodsNumCache(){
    storage.remove(goods_cache_key);
  }

}

export {
  GoodsNumCache
}